package com.tarena.lbs.business.dao.repository.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tarena.lbs.business.dao.mapper.StoreChainMapper;
import com.tarena.lbs.business.dao.mapper.StoreMapper;
import com.tarena.lbs.business.dao.repository.StoreRepository;
import com.tarena.lbs.business.pojo.param.UserLocationParam;
import com.tarena.lbs.business.pojo.po.StoreChainPO;
import com.tarena.lbs.business.pojo.po.StorePO;
import com.tarena.lbs.business.pojo.query.AreaStoreQuery;
import com.tarena.lbs.business.pojo.query.StoreChainQuery;
import com.tarena.lbs.business.pojo.query.StoreQuery;
import com.tarena.lbs.business.pojo.vo.StoreVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.geo.GeoPoint;
import org.springframework.stereotype.Repository;
import org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.Criteria;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;
import com.tarena.lbs.business.pojo.po.StoreSearchPO;

import java.util.List;
import java.util.stream.Collectors;
@Slf4j
@Repository
public class StoreRepositoryImpl implements StoreRepository {


    @Autowired
    private StoreMapper storeMapper;
    
    // 添加ElasticsearchTemplate依赖
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @Autowired
    private StoreChainMapper storeChainMapper;


    @Override
    public void save(StorePO storePO) {
        //查询店铺是否存在，存在则更新，不存在则插入
        QueryWrapper<StorePO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", storePO.getId());
        StorePO existingStore = storeMapper.selectOne(queryWrapper);
        if (existingStore != null) {
            storeMapper.updateById(storePO);
        } else {
            storeMapper.insert(storePO);
        }
    }

    @Override
    public PageInfo<StorePO> pagesList(StoreQuery query) {
        QueryWrapper<StorePO> queryWrapper = assembleStoreQuery(query);
        PageHelper.startPage(query.getPageNo(), query.getPageSize());
        List<StorePO> pos = storeMapper.selectList(queryWrapper);
        return new PageInfo<>(pos);
    }

    @Override
    public PageInfo<StorePO> areaPagesList(AreaStoreQuery query, Integer businessId) {
        QueryWrapper<StorePO> queryWrapper = assembleAreaStoreQuery(query, businessId);
        PageHelper.startPage(query.getPageNo(), query.getPageSize());
        List<StorePO> pos = storeMapper.selectList(queryWrapper);
        return new PageInfo<>(pos);
    }

    @Override
    public StorePO getById(Integer id) {
        return storeMapper.selectById(id);
    }
    
    @Override
    public List<StoreVO> findNearbyStores(UserLocationParam param) {
        try {
            // 将字符串转换为double
            double lat = Double.parseDouble(param.getLatitude());
            double lon = Double.parseDouble(param.getLongitude());
            
            // 创建Criteria查询附近5公里内的店铺
            Criteria criteria = new Criteria("location").within(new GeoPoint(lat, lon), "5km");
            CriteriaQuery criteriaQuery = new CriteriaQuery(criteria);
            
            // 执行查询
            SearchHits<StoreSearchPO> searchHits = 
                elasticsearchTemplate.search(criteriaQuery, StoreSearchPO.class);
            
            // 转换结果
            return searchHits.get().map(hit -> {
                StoreSearchPO storeSearchPO = hit.getContent();
                StoreVO storeVO = new StoreVO();
                // 映射字段
                storeVO.setId(storeSearchPO.getId());
                storeVO.setStoreName(storeSearchPO.getStoreName());
                storeVO.setBusinessId(storeSearchPO.getBusinessId());
                // 根据实际情况添加其他字段映射
                return storeVO;
            }).collect(Collectors.toList());
        } catch (NumberFormatException e) {
            // 经纬度格式不正确时返回空列表
            log.debug("经纬度格式不正确: latitude={}, longitude={}", param.getLatitude(), param.getLongitude());
            return List.of();
        } catch (Exception e) {
            // 其他异常也返回空列表
            log.debug("查询附近店铺时发生异常: ", e);
            return List.of();
        }
    }

    @Override
    public PageInfo<StoreChainPO> getChain(StoreChainQuery query) {
                // 1.storeName 门店名称 模糊查询 where store_name like '%#{storeName}%'
                QueryWrapper<StoreChainPO> queryWrapper = new QueryWrapper<>();
                if (StringUtils.isNotBlank(query.getStoreName())) {
                    queryWrapper.like("store_name", query.getStoreName());
                }
                // 2.storeAddress 门店地址 模糊查询 where store_address like '%#{storeAddress}%'
                if (StringUtils.isNotBlank(query.getStoreAddress())) {
                    queryWrapper.like("store_address", query.getStoreAddress());
                }
                // 3.其他条件...
                PageHelper.startPage(query.getPageNo(), query.getPageSize());
                List<StoreChainPO> pos = storeChainMapper.selectList(queryWrapper);
                return new PageInfo<>(pos);
    }

    @Override
    public void delete(Integer id) {
        log.debug("删除店铺业务处理,入参:{}",id);
        storeMapper.deleteById(id);
    }

    private QueryWrapper<StorePO> assembleStoreQuery(StoreQuery query) {
        QueryWrapper<StorePO> queryWrapper = new QueryWrapper<>();
        //1.storeName 门店名称 模糊查询 where store_name like '%#{storeName}%'
        if (StringUtils.isNotBlank(query.getStoreName())) {
            queryWrapper.like("store_name", query.getStoreName());
        }
        //2.storeHeadPhone 负责人电话 精确查询 where store_head_phone = storeHeadPhone
        if (StringUtils.isNotBlank(query.getStoreHeadPhone())) {
            queryWrapper.eq("store_head_phone", query.getStoreHeadPhone());
        }
        //3.provinceId 省份 精确查询 where province_id = provinceId
        if (query.getProvinceId() != null) {
            queryWrapper.eq("province_id", query.getProvinceId());
        }
        //4.cityId 市 精确查询 where city_id = cityId
        if (query.getCityId() != null) {
            queryWrapper.eq("city_id", query.getCityId());
        }
        //5.areaId 区 精确查询 where area_id = areaId
        if (query.getAreaId() != null) {
            queryWrapper.eq("area_id", query.getAreaId());
        }
        //6.businessId 商家ID 精确查询 where business_id = businessId
        if (query.getBusinessId() != null) {
            queryWrapper.eq("business_id", query.getBusinessId());
        }
        //7.storeStatus 门店状态（是否启用）0 启用  -1禁用 精确查询 where store_status = storeStatus
        if (query.getStoreStatus() != null) {
            queryWrapper.eq("store_status", query.getStoreStatus());
        }
        return queryWrapper;
    }

    private QueryWrapper<StorePO> assembleAreaStoreQuery(AreaStoreQuery query, Integer businessId) {
        QueryWrapper<StorePO> queryWrapper = new QueryWrapper<>();
        if (query.getCityIdList() != null){
            queryWrapper.in("area_id", query.getCityIdList());
        }
        if (businessId != null){
            queryWrapper.eq("business_id", businessId);
        }
        return queryWrapper;
    }
}